//
//  MusicViewWithTableViewController.m
//  One
//
//  Created by mac on 16/5/26.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "MusicViewWithTableViewController.h"
#import "HeadViewTableViewCell.h"
#import "ContentTableViewCell.h"
#import "CommentTableViewCell.h"
#import "ChooseTableViewCell.h"
#import "LyircAndInfoTableViewCell.h"
#import "MusicRequest.h"
#import "MusicPlay.h"
#import "MusicPlayBarButton.h"

const MusicViewWithTableViewController *tableMusicViewControll;

@interface MusicViewWithTableViewController ()<UITableViewDelegate,UITableViewDataSource>
{
//    UITableView *myTableView;
    NSMutableArray *commentsArray;
    NSMutableArray *commentsHotArray;
    int tagCount;
    int lastCommentId;
    int playButtonClickCount;
    int getDataCount;
    MusicPlay *musicPlay;
}
@end

NSString *const ConentReuseIdStr = @"content";
NSString *const CommentReuseIdStr = @"comment";
NSString *const HeadReuseIdStr = @"head";
NSString *const ChooseReuseIdStr = @"choose";
NSString *const DefaultReuseIdStr = @"default";
NSString *const LyircAndInfoReuseIdStr = @"lyircAndInfo";

@implementation MusicViewWithTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    musicPlay = [MusicPlay shareAVPlay];
    [self initialization];
    [NOTI_CENTER addObserver:self selector:@selector(changeCell) name:@"play" object:nil];
}

- (void)initialization
{
    lastCommentId = 0;
    playButtonClickCount = 0;
    getDataCount = 0;
    commentsArray = [[NSMutableArray alloc]init];
    commentsHotArray = [[NSMutableArray alloc]init];
    
    _myTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT) style:UITableViewStyleGrouped];
    
    _myTableView.delegate = self;
    _myTableView.dataSource = self;
    _myTableView.sectionFooterHeight = 0.00001;
    //内容
    [_myTableView registerNib:[UINib nibWithNibName:@"ContentTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:ConentReuseIdStr];
    //评论
    [_myTableView registerNib:[UINib nibWithNibName:@"CommentTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:CommentReuseIdStr];
    //头部视图不是头区间视图
    [_myTableView registerNib:[UINib nibWithNibName:@"HeadViewTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:HeadReuseIdStr];
    //评论 点赞 分享按钮
    [_myTableView registerNib:[UINib nibWithNibName:@"ChooseTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:ChooseReuseIdStr];
    //info lyirc
    [_myTableView registerNib:[UINib nibWithNibName:@"LyircAndInfoTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:LyircAndInfoReuseIdStr];
    
    [_myTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:DefaultReuseIdStr];
    
    _myTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLineEtched;
    
    _myTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self getCommentArrayWithObject:_musicObject LastId:lastCommentId];
        
    }];
    self.type = story;
    
    [self getCommentArrayWithObject:_musicObject LastId:lastCommentId];
    [self.view addSubview:_myTableView];
}

- (void)getCommentArrayWithObject:(MusicModleObject *)musicModelObject LastId:(int) lastCommtsId
{
  
    [MusicRequest musicCommentsWithMusicId:musicModelObject.ID LastCommentId:lastCommentId withBlock:^(musicCommentsModelObject *object, NSArray *hotCommentsArr, NSArray *commentsArr) {
        getDataCount ++;
        
        _musicCommentObject = object;
        
        [hotCommentsArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [commentsHotArray addObject:obj];
        }];
        
        [commentsArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            {
                [commentsArray addObject:obj];
            }
        }];
        
        musicCommentsObject *obj = commentsArray.lastObject;
        lastCommentId = obj.Id;
        NSMutableIndexSet *indexSet=[[NSMutableIndexSet alloc]init];
        
        if (getDataCount == 1) {
            [indexSet addIndex:2];
            [indexSet addIndex:3];
            [_myTableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
        }
        else if (getDataCount > 1) {
            [_myTableView reloadData];
        }
        
        [_myTableView.mj_footer endRefreshing];
    }];

}

#pragma mark -UITableViewDelegate

- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(_musicObject)
    {
        if (section == 3) {
            return commentsArray.count;
        }
        else if (section == 2) {
            return commentsHotArray.count;
        }
        else if (section == 1)
            return 2;
        else
            return 1;
    }
    else
    {
        if (section == 0) {
            return 1;
        }
        
        return 0;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 2||section == 3) {
        return 44;
    }
    return 0.001;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *commentsView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 44)];

    if (section == 2) {
        
        commentsView.backgroundColor = [UIColor colorWithWhite:0.949 alpha:1.000];
        UILabel *commentsLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 7, WIDTH - 20, 30)];
        commentsLabel.text = @"评论列表";
        [commentsView addSubview:commentsLabel];
        return commentsView;
    }
    if (section == 3) {
        commentsView.backgroundColor = [UIColor whiteColor];
        UILabel *label = [[UILabel alloc]init];
        label.center = commentsView.center;
        label.text = @"以上是热门评论";
        label.textAlignment = NSTextAlignmentCenter;
        label.textColor = [UIColor colorWithRed:0.325 green:0.592 blue:0.980 alpha:1.000];
        label.bounds = CGRectMake(0, 0, 140, 44);
        [commentsView addSubview:label];
        UIView *line1 = [[UIView alloc]init];
        UIView *line2 = [[UIView alloc]init];
        line1.frame = CGRectMake(5, commentsView.center.y - 2, (WIDTH - 40 - 140)/2 - 5, 1);
        line1.backgroundColor = [UIColor colorWithRed:0.729 green:0.847 blue:0.996 alpha:1.000];
        line2.frame = CGRectMake(CGRectGetMaxX(label.frame) + 20 , commentsView.center.y - 2,(WIDTH - 40 - 140)/2 - 5, 1);
        line2.backgroundColor = [UIColor colorWithRed:0.729 green:0.847 blue:0.996 alpha:1.000];
        
        [commentsView addSubview:line1];
        [commentsView addSubview:line2];
        return commentsView;
    }
    return nil;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {

        return WIDTH + 100;
    }
    else if (indexPath.section == 1)
    {
        if (indexPath.row == 0) {
            if (_type == 0) {
                
                
                return  [self caculateHeightWithStr:_musicObject.story FontSize:16 Width:20] + 50;
            }
            else if(_type == 1)
            {
                return [self caculateHeightWithStr:_musicObject.lyric FontSize:16 Width:20] + 50;
            }
            else
            {
                return [self caculateHeightWithStr:_musicObject.info FontSize:16 Width:20] + 50;
            }
        }
        else
            return 100;
    }
    else{
        musicCommentsObject *commObj = nil;
        if(indexPath.section == 2)
        {
            commObj = commentsHotArray[indexPath.row];
        }
        else
        {
            commObj = commentsArray[indexPath.row];
        }
        return [self caculateHeightWithStr:commObj.content FontSize:16 Width:60] + 60;
    }

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    /**
     *  0： 头
     *  1： a.内容 b.按钮cell
     *  2： 热评
     *  3： 普通评论
     */
    UITableViewCell *cell = nil;
    //头
    if(indexPath.section == 0)
    {

        HeadViewTableViewCell  *cell1 = [tableView dequeueReusableCellWithIdentifier:HeadReuseIdStr forIndexPath:indexPath];

        cell1.musicCoverImageView.image = [UIImage imageNamed:@"music_cover.jpg_unsliced"];
        [MBProgressHUD showHUDAddedTo:cell1.musicCoverImageView animated:YES];
        [cell1.musicAuthorImageButton setImage:nil forState:UIControlStateNormal];
        
        switch (_type) {
            case 0:
                cell1.currentTitle.text = @"音乐故事";
                break;
            case 1:
                cell1.currentTitle.text = @"歌词";
                break;
            case 2:
                cell1.currentTitle.text = @"歌曲信息";
                break;
        }
        [cell1.musicCoverImageView sd_setImageWithURL:[NSURL URLWithString:_musicObject.cover]completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            [MBProgressHUD hideAllHUDsForView:cell1.musicCoverImageView animated:YES];
        }];
        cell1.musicAuthorInfo.text = _musicObject.desc;
        cell1.musicName.text = _musicObject.title;
            
        [cell1.musicAuthorImageButton sd_setImageWithURL:[NSURL URLWithString:_musicObject.author_web_url] forState:UIControlStateNormal];
        [cell1.musicAuthorNameButton setTitle:_musicObject.author_user_name forState:UIControlStateNormal];
        if (musicPlay.currenPlayItem.ID == _musicObject.ID) {
            if (musicPlay.isPlaying) {
                cell1.playButton.selected = YES;
            }
            else
                cell1.playButton.selected = NO;
        }
        
        [cell1.playButton addTarget:self action:@selector(playMusicButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        cell1.dateLabel.text = [self WeekWithMakeTime:_musicObject.maketime];
        [cell1.storyButton addTarget:self action:@selector(meunButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [cell1.lyricButton addTarget:self action:@selector(meunButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [cell1.infoButton addTarget:self action:@selector(meunButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        
        cell = cell1;

    }
    //内容
    else if (indexPath.section == 1)
    {
        switch (indexPath.row) {
            case 0:
            {
                if (_type == 0)
                {
                    ContentTableViewCell *cell1 = [tableView dequeueReusableCellWithIdentifier:ConentReuseIdStr forIndexPath:indexPath];
                    cell1.storyLabel.text = [self changeHTMLTagWithStr:_musicObject.story];
                    cell1.stroyNameLabel.text = _musicObject.story_title;
                    [cell1.author setTitle:_musicObject.story_user_name forState:UIControlStateNormal];
                    cell1.author.titleLabel.textAlignment = NSTextAlignmentLeft;
                    cell1.editerLabel.text = _musicObject.charge_edt;
                    cell = cell1;
                }
                else
                {
                    LyircAndInfoTableViewCell *cell1 = [tableView dequeueReusableCellWithIdentifier:LyircAndInfoReuseIdStr forIndexPath:indexPath];
                    if (_type == 1) {
                        cell1.infoOrLyricLabel.text = _musicObject.lyric;
                        
                    }
                    else
                    {
                        cell1.infoOrLyricLabel.text = _musicObject.info;
                    }
                    cell1.editorLabel.text = _musicObject.charge_edt;
                    cell = cell1;
                }
            }
            break;
                
            default:
            {
                ChooseTableViewCell *cell1 = [tableView dequeueReusableCellWithIdentifier:ChooseReuseIdStr forIndexPath:indexPath];
                
                cell = cell1;
            }
            break;
        }

    }
    //评论
    else
    {
        musicCommentsObject *commObj = nil;
        CommentTableViewCell *cell1 = [tableView dequeueReusableCellWithIdentifier:CommentReuseIdStr forIndexPath:indexPath];
        if (indexPath.section == 2) {
                commObj = commentsHotArray[indexPath.row];
        }
        else
        {
            commObj = commentsArray[indexPath.row];
        }
        cell1.commentContentLabel.text = commObj.content;
        cell1.userNameLabel.text = commObj.user_name;
        cell1.likeNunLabel.text = [@(commObj.praisenum) stringValue];
        cell1.makeTimeLaebl.text = commObj.input_date;
        [cell1.headImageViewButton sd_setImageWithURL:[NSURL URLWithString:commObj.web_url] forState:UIControlStateNormal];
        cell = cell1;
    }
    
    return cell;
}

#pragma mark -计算文章高度 并没有什么卵用
- (CGFloat)caculateHeightWithStr:(NSString *)str FontSize:(CGFloat)fontSize Width:(CGFloat)width
{
    CGRect rect = [str boundingRectWithSize:CGSizeMake(WIDTH - width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:fontSize]} context:nil];
    return rect.size.height;
}

#pragma mark -清除文章中的HTML标签
- (NSString *)changeHTMLTagWithStr:(NSString *)str
{
    NSString *changeStr = [str stringByReplacingOccurrencesOfString:@"<br>" withString:@""];
    NSString *changStr1 = [changeStr stringByReplacingOccurrencesOfString:@"<strong>" withString:@""];
    NSString *changStr2 = [changStr1 stringByReplacingOccurrencesOfString:@"</strong>" withString:@""];
    
    return changStr2;
}

#pragma mark -日期转变
- (NSString *)WeekWithMakeTime:(NSString *)makeTime
{
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"YYYY-MM-DD"];
    
    NSArray *arr = [makeTime componentsSeparatedByString:@" "];
    
    NSString *weekDay = arr[0];
    NSString *year = [weekDay componentsSeparatedByString:@"-"][0];
    int MonthDay = [[weekDay componentsSeparatedByString:@"-"][1] intValue];
    NSString *day = [weekDay componentsSeparatedByString:@"-"][2];
    
    NSArray *monthArr = [NSArray arrayWithObjects:[NSNull null],@"Jan.",@"Feb.",@"Mar.",@"Apr.",@"May.",@"Jun.",@"Jul.",@"Aug.",@"Sep.",@"Oct.",@"Nov.",@"Dec.", nil];

    NSString *mounth = monthArr[MonthDay];
    
    NSString *dateStr = [NSString stringWithFormat:@"%@ %@,%@",mounth,day,year];
    return dateStr;
}

#pragma mark -ButtonClickMethod

- (void)playMusicButtonClick:(UIButton *)sender
{
    playButtonClickCount ++;
    _musicObject.isPlay = sender.selected = !sender.selected ;

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{

        UIWindow *window = [[[UIApplication sharedApplication]delegate]window];
        [window addSubview:[[MusicPlayBarButton alloc] init]];
    
    });
    
    NSLog(@"%@",_musicObject.music_id);
    if ([sender isSelected]) {
        if (playButtonClickCount == 1) {
            if (_currentPage == 0) {
                [musicPlay playMusicWithUrl:[NSURL URLWithString:_musicObject.music_id]CurrentPlayItem:_musicObject];
            }
            else
                [musicPlay playAnthorMusicWithUrl:[NSURL URLWithString:_musicObject.music_id] CurrentPlayItem:_musicObject];
        }
    }
    
    [musicPlay doPlay];
}

- (void)meunButtonClick:(UIButton *)sender
{
    if (sender.selected == NO) {
        sender.selected = !sender.selected;
        NSIndexPath *index = [NSIndexPath indexPathForRow:0 inSection:0];
        
        HeadViewTableViewCell *cell = [_myTableView cellForRowAtIndexPath:index];
        
        if (sender == cell.storyButton) {
            cell.lyricButton.selected = cell.infoButton.selected =  !sender.selected;
            _type = story;
        }
        else if(sender == cell.lyricButton)
        {
            cell.storyButton.selected =cell.infoButton.selected =  !sender.selected;
            _type = lyric;
        }
        else
        {
            cell.storyButton.selected =cell.lyricButton.selected =  !sender.selected;
            _type = info;
        }

        [_myTableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:1]] withRowAnimation:UITableViewRowAnimationNone];
    }
    
}

- (void)changeCell
{
    
    NSIndexPath *index = [NSIndexPath indexPathForRow:0 inSection:0];
    HeadViewTableViewCell *cell1 = [_myTableView cellForRowAtIndexPath:index];
    
    if (musicPlay.currenPlayItem.ID == _musicObject.ID) {
        if (musicPlay.isPlaying) {
            cell1.playButton.selected = YES;
        }
        else
            cell1.playButton.selected = NO;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
